package com.ifgostudio.framework.web.servlet.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.ifgostudio.framework.exception.handler.SpringMVCExceptionHandler;

/**
 * <b>Description</b>:服务执行时间的记录,拦截器是单例，因此不管用户请求多少次都只有一个拦截器实现，即线程不安全,所以我们使用ThreadLocal<br/>
 * <b>Author</b>: linxuexin<br/>
 * <b>Link</b>: Email:<a href="mailto:linxuexin0423@gmail.com">linxuexin0423@gmail.com</a>;Telephone:13799286849;QQ:30268646;林先生<br/>
 * <b>Copyright</b>: <a href="http://www.ifgostudio.com" target="_blank">www.ifgostudio.com</a> all rights reserved<br/>
 * <b>Information</b>: 对外承接网站制作,价格优惠,服务一流,强有力的技术支持,asp,Jsp,PHP,MySQL,Hibernate,Struts2,MS SQLServer,Oracle,jQuery,Css+div布局,Dhtml<br/>
 * <b>Create Date</b>: 2013-3-13 下午4:27:52<br/>
 * <b>Version</b>: Since JDK 1.6.0<br/>
 * <b>Package</b>: com.ifgostudio.framework.web.servlet
 */
public class StopWatchInterceptor extends HandlerInterceptorAdapter {
	
	private static final Logger logger = LoggerFactory.getLogger(SpringMVCExceptionHandler.class); 
	private static final ThreadLocal<Long>  startTimeThreadLocal = new ThreadLocal<Long>();

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		long beginTime = System.currentTimeMillis();//1、开始时间
		startTimeThreadLocal.set(beginTime);
		return super.preHandle(request, response, handler);
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		long endTime = System.currentTimeMillis();//2、结束时间  
		long beginTime = startTimeThreadLocal.get();//得到线程绑定的局部变量（开始时间）  
		long consumeTime = endTime - beginTime;//3、消耗的时间  
		if(consumeTime > 5000) {//此处认为处理时间超过5秒的请求为慢请求  
			if(logger.isInfoEnabled())
				logger.info(String.format("%s consume %d millis", request.getRequestURI(), consumeTime));
		}    
		super.afterCompletion(request, response, handler, ex);
	}
}
